<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Model\Libs;


use Selibra\Tools\Console;
use Selibra\Model\SFEntity;
use Selibra\Model\SFModel;

class Pager
{

    /**
     * @var SFModel
     */
    private SFModel $model;


    /**
     * @var PagerConf
     */
    private PagerConf $config;


    /**
     * 总数量
     * @var int
     */
    private int $total;


    /**
     * 查询条件
     * @var string
     */
    private string $conditionSql;


    /**
     * Pager constructor.
     * @param SFModel $model
     * @param PagerConf $pagerConf
     */
    public function __construct(SFModel $model, PagerConf $pagerConf)
    {
        $this->model = $model;
        $this->config = $pagerConf;
    }


    /**
     * @return SFEntity[]
     */
    public function getResult()
    {
        $start = (($this->config->getCurrent() - 1) * $this->config->getSize());
        $this->model->setLimit($start, $this->config->getSize());
        return $this->model->select();
    }


    /**
     * 获取所有
     * @return int
     */
    public function getTotal()
    {
        if (!isset($this->total)) {
            // 开始数量，(current - 1) * size + 1
            $sql = "SELECT count(*) as count FROM " . $this->model->getTable() . " " . $this->getConditionSql();
            $countResult = $this->model->query($sql, true);
            $this->total = $countResult[0]['count'] ?: 0;
        }
        return $this->total;
    }


    /**
     * 获取分页数量
     * @return float
     */
    public function getCountPage()
    {
        if (empty($this->total)) {
            return 0;
        }
        $allPage = ceil($this->getTotal() / $this->config->getSize());
        return $allPage;
    }


    private function getConditionSql()
    {
        if (!isset($this->conditionSql)) {
            $this->conditionSql = $this->model->getSqlBuilder()->getConditionSql();
        }
        return $this->conditionSql;
    }


    /**
     * 返回数组结构数据
     * @return array
     */
    public function toArrayData()
    {
        return [
            'current' => $this->config->getCurrent(),
            'size' => $this->config->getSize(),
            'total' => $this->getTotal(),
            'countPage' => $this->getCountPage(),
            'result' => $this->getResult() ?: [],
        ];
    }
}